package cn.htsyb.synergy.maker.util;

import java.io.*;
import java.nio.charset.Charset;

public class StreamUtil {
    public static final int BUFFER_SIZE = 4096;

    public static String readContent(final InputStream input, final Charset encoding) throws IOException {
        try (final StringWriter sw = new StringWriter();
             InputStreamReader in = new InputStreamReader(input, encoding)) {
            transferStream(in, sw);
            return sw.toString();
        }
    }

    public static void transferStream(final Reader in, final Writer out) throws IOException {
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }

    public static void transferStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }
}
